#!/usr/bin/env python
# -*- coding: utf-8 -*-

import matplotlib.lines as lines
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import rcParams

rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['HarmonyOS Sans SC', 'Microsoft YaHei', 'Ubuntu Mono']
rcParams['font.size'] = 24

data = (
    {
        'xlab': '负载轨迹',
        'group': ('LRU', 'Mithril', 'Emith'),
        'x': ('backup', 'gsf-filesrv', 'moodle', 'ug-filesrv', 'usr1', 'usr2'),
        # 'hr_lru': (0, 0, 0, 0, 0, 0),
        'hr': (
            (0.455631, 0.867724, 0.680202, 0.857463, 0.820648, 0.984201),
            (0.457196, 0.850651, 0.786034, 0.860912, 0.837052, 0.965902),
            (0.460247, 0.918034, 0.817674, 0.872599, 0.899704, 0.986720),
        ),
        # 'hr_min': (0, 0, 0, 0, 0, 0),
        'hrlim': (0, 100),
        'output_hr': 'figures/Fig_FIU_hr.png',
    },
    {
        'xlab': '负载轨迹',
        'group': ('Emith'),
        'x': ('backup', 'gsf-filesrv', 'moodle', 'ug-filesrv', 'usr1', 'usr2'),
        'tm': (
            np.array((7.27890380, 2.8027179, 12.7142135, 51.282810, 2.8868536, 0.9324935), dtype=float) / \
            np.array((20.5625571, 10.114820, 14.3286464, 62.876698, 6.4321998, 4.9121923), dtype=float)
        ),
        'xwidth': 0.55,
        'baseline': 1.0,
        'bar_label': 'edge',
        # 'tmlim': (0, 1.2),
        'xlim': (-0.6, 5.6),
        'output_tm': 'figures/Fig_FIU_tm.png',
    },
)


def main_hr(
    group=(),  color=('tab:blue', 'tab:orange', 'tab:green'), hatch=('', '', ''),
    hr=(),  hr_lru=None, hr_min=None, hrlim=None,
    x=None, xlab='', xwidth=0.27,
    output_hr=None, **kwargs
):
    fig = plt.figure(figsize=(14, 9))  # create figure
    ax = plt.axes(position=[0.085, 0.11, 0.9, 0.78])  # create axes

    N = len(x)
    G = len(group)
    X = np.array(range(N), dtype=float)

    nhr = np.array(hr, dtype=float) * 100  # to 100%

    for i in range(G):
        style_hr = {'color': color[i], 'hatch': hatch[i], 'edgecolor': 'k', 'linewidth': 2.5}
        ax.bar(X + xwidth * i, nhr[i, :], xwidth, label=group[i], ** style_hr)

    if hr_lru:
        lru_x = []
        lru_y = []
        for i in range(N):
            h = hr_lru[i] * 100
            lru_x.extend([i - xwidth * 0.7, i + xwidth * (G-0.3), None])
            lru_y.extend([h, h, None])
        ax.plot(lru_x, lru_y, label='LRU', linewidth=3.5, color='k')

    if hr_min:
        min_x = []
        min_y = []
        for i in range(N):
            h = hr_min[i] * 100
            min_x.extend([i - xwidth * 0.7, i + xwidth * (G-0.3), None])
            min_y.extend([h, h, None])
        ax.plot(min_x, min_y, '--', label='MIN', linewidth=3, color='k')

    if hrlim:
        ax.set_ylim(hrlim)
    ax.set_ylabel('缓存命中率 (%)')

    ax.set_xticks(X + xwidth * (G-1) / 2)
    if x:
        ax.set_xticklabels(x)

    ax.set_xlabel(xlab)
    ax.legend(bbox_to_anchor=(0.49, 1.125), loc=9, ncol=5, edgecolor='1')

    if type(output_hr) == str:
        if False:
            fig.add_artist(lines.Line2D([0, 1], [0, 1]))
            fig.add_artist(lines.Line2D([0, 1], [1, 0]))
            fig.add_artist(lines.Line2D([0, 0, 1, 1, 0], [0, 1, 1, 0, 0]))
        plt.savefig(output_hr)
    pass


def main_tm(
    group=(), color=('tab:blue', 'tab:orange', 'tab:green'), hatch=('', ''),
    tm=(), tmlim=None, baseline=None, bar_label=None,
    x=None, xlab='', xwidth=0.27, xlim=None,
    output_tm=None, **kwargs
):
    fig = plt.figure(figsize=(14, 9))  # create figure
    ax = plt.axes(position=[0.1, 0.11, 0.88, 0.78])  # create axes

    N = len(x)
    G = len(group)
    X = np.array(range(N), dtype=float)

    data = np.array(tm, dtype=float)
    if data.ndim == 1:
        data = data.reshape((1, N))
        group = [group]
        G = 1  # only one group
    print(N, G, data)

    for i in range(G):
        style_tm = {'color': color[i], 'hatch': hatch[i], 'edgecolor': 'k', 'linewidth': 2.5}
        hb = ax.bar(X + xwidth * i, data[i, :], xwidth, label=group[i], ** style_tm)
        if bar_label:
            ax.bar_label(hb, ['%.4f' % x for x in data[i, :]], label_type=bar_label)

    if baseline:
        bx = [-xwidth, N - 1 + xwidth, None]
        by = [baseline, baseline, None]
        ax.plot(bx, by, '--', linewidth=3, color='k')

    if tmlim:
        ax.set_ylim(tmlim)
    ax.set_ylabel('相对运行时间')

    ax.set_xticks(X + xwidth * (G-1) / 2)
    if x:
        ax.set_xticklabels(x)
    if xlim:
        ax.set_xlim(xlim)
    ax.set_xlabel(xlab)
    ax.legend(bbox_to_anchor=(0.49, 1.125), loc=9, ncol=5, edgecolor='1')

    if type(output_tm) == str:
        if False:
            fig.add_artist(lines.Line2D([0, 1], [0, 1]))
            fig.add_artist(lines.Line2D([0, 1], [1, 0]))
            fig.add_artist(lines.Line2D([0, 0, 1, 1, 0], [0, 1, 1, 0, 0]))
        plt.savefig(output_tm)
    pass


main_hr(**data[0])
main_tm(**data[1])
